import React from 'react';
import classNames from 'classnames';
import { Link } from 'react-router';

import {
  Row,
  Col,
  Panel,
  Button,
  Collapse
} from 'react-bootstrap';

import * as Util from '../common/Util';

import { product as ProductConfig, domain } from '../config/Common';

class ProductItem extends React.Component {

  constructor() {
    super();

    this.praiseHistoryStatus = 0;

    this.state = {
       product_data_open : false
    };
  }

  static propTypes = {
      handleProductSign : React.PropTypes.func
  }

  handleDetailClick (e){
    let product_data_open  = this.state.product_data_open;
    this.setState({
      product_data_open : !product_data_open
    });

    let { handleProductDetail } = this.props;
    if (handleProductDetail && product_data_open===false) {
      handleProductDetail(e);
    }
  }

  handleUnSignClick(e){
    let { handleProductUnSign } = this.props;

    handleProductUnSign(e); 
  }

  handleSignClick(e){
    let { handleProductSign } = this.props;

    handleProductSign(e); 
  }

  getRenderStyle(val){
    let isHappy = (parseFloat(val) >= 0 ? true : false);
    let happyClass = {
        "text-success": !isHappy,
        "text-danger": isHappy
    };
    let currentClass = classNames( happyClass );

    return currentClass;
  }

  handleHistoryLike(history, event){
    let { product } = this.props;

    if(this.praiseHistoryStatus === 0){

      this.praiseHistoryStatus = 1;

      let dataParam = {
        pid : product.gsid,
        mid : history.mid
      };
      this.props.productAction.praiseHistory(dataParam);
    }
  }

  componentDidUpdate(){
    this.praiseHistoryStatus = 0;
  }

  filterProductHistory(history){
    let result = [];
    if (history && history.length > 0) {

      history.sort(function(a,b){
          var time_a = a.jydatetime,
              time_b = b.jydatetime;

          time_a = Util.DateFormater(time_a, "yyyyMMddhhmmss");
          time_b = Util.DateFormater(time_b, "yyyyMMddhhmmss");
          return time_b - time_a;
      });

      for (let i = 0, len = history.length; i < len; i++) {
        let historyItem = history[i];
        //应业务要求，仅两条显示卖出
        if (historyItem.operate === "2") {
          result.push(historyItem);
        }
        if (result.length === 1) {
          break;
        }
      }
    }

    return result;
  }

  render(){

      let { product, user } = this.props;

      let profitClass = (parseFloat(product.tdprofit) >= 0 ? "text-danger" : "text-success");

      let productHistory = this.filterProductHistory(product.history);

      let currentTime = Util.DateFormater(new Date(), "MM-dd hh:mm:ss");
      
      return (
          <Panel className="product-item">
            <div className="product-avatar">
              <Link to={`/ProductDetail`} query={{id:product.gsid}}>
                <img src={`${domain}${product.avatar}`} className="img-circle"/>
              </Link>
              <br/>
              {
                product.status === ProductConfig.productStatus.hasSign ? 
                <a className="text-muted border-bottom-muted" onClick={ this.handleUnSignClick.bind(this) }>
                  <small>已关注</small>
                </a>
                :
                <label className="text-info">
                  关注数：{product.viewcount || 0}
                </label>
              }
            </div>
            <div className="product-detail" onClick={ this.handleDetailClick.bind(this) }>
                <h4 className="text-info title">
                  {product.name}
                </h4>
                <label className="text-info">
                  { product.gstype == ProductConfig.productType.short?'最近30日':"最近60日" }
                </label>
                <p className="text-info item">
                    <label>均笔收益率：</label>
                    <span className={profitClass}>
                      { `${parseFloat(product.tdprofit).toFixed(2)}%` }
                    </span>
                </p>
                <p className="text-info item">
                    <label>成功率：</label>
                    <span className="text-danger">
                      { `${parseFloat(product.tdsuccessrate).toFixed(2)}%` }
                    </span>
                </p>
            </div>
            <div className="product-op">
              {
                product.status === ProductConfig.productStatus.hasSign?
                <a className="text-danger" onClick={ this.handleDetailClick.bind(this) }>
                  持仓情况
                </a>
                :
                <img src="http://o2o.hx168.com.cn/hxfinance/Public/Upload/Image/2015-10-15/1444901308.png"  
                  onClick={ this.handleSignClick.bind(this) }/>
              }
            </div>

            <div className="blank20"></div>

            <Collapse in={ this.state.product_data_open }>
              <div className="product-data"> 
                  <Panel header="当前持仓" footer={`更新时间：${currentTime}`} className="panel-thin">
                    {
                        !product.holding ?
                        <div className="text-center">
                          加载中
                        </div>
                        :
                        product.holding && product.holding.length  > 0 ?
                        product.holding.map((holding, i) =>{
                            return (
                              <Row className="product-data-row margin-bottom">
                                <Col xs={3} className="holding-stockname">
                                    <p>
                                      {holding.stockname}
                                    </p>
                                    <p>
                                      {holding.stockcode}
                                    </p>
                                </Col>
                                <Col xs={3}  className="holding-price">
                                    <p>
                                        现价&nbsp;{holding.nowprice}
                                    </p>
                                    <p>
                                        成本&nbsp;{parseFloat(holding.costprice).toFixed(2)}
                                    </p>
                                </Col>
                                <Col xs={3}  className="holding-position">
                                    <p className="product-data-single">
                                        仓位&nbsp;{
                                          holding.position?
                                          `${parseFloat(holding.position).toFixed(2)}%`
                                          :
                                          `—`
                                        }
                                    </p>
                                </Col>
                                <Col xs={3}  className="holding-profit">
                                    <p className="product-data-single">
                                      盈亏&nbsp;<span className={ this.getRenderStyle(holding.profit) }>{ parseFloat(holding.profit).toFixed(2) }%</span>
                                    </p>
                                </Col>
                              </Row>
                            );
                        }) 
                        :
                        <div className="text-center">
                          暂无策略持仓
                        </div>
                    }
                  </Panel>
                  <Panel header="策略观点" className="panel-thin">
                    {product.gscomment || "暂时没什么可说的。"}
                  </Panel>
                  <Panel header="近期操作" className="panel-thin">
                    {
                      !product.history ?
                      <div className="text-center">
                          加载中
                      </div>
                      :
                      productHistory && productHistory.length > 0 ?
                      productHistory.map((history, i) =>{
                          return (
                              <Row className="product-data-row">
                                <Col xs={3}>
                                    <p>
                                        {history.stockname}
                                    </p>
                                    <p>
                                        {history.stockcode}
                                    </p>
                                </Col>
                                <Col xs={3}>
                                    <p>
                                        操作&nbsp;
                                        {
                                          history.operate === "2"?
                                          `卖出`
                                          :
                                          `买入`
                                        }
                                    </p>
                                    <p>
                                        时间&nbsp;{Util.DateFormater(history.jydatetime, "MM-dd")}
                                    </p>
                                </Col>
                                <Col xs={4}>
                                    <p>
                                      盈亏&nbsp;
                                      { 
                                        history.operate === "2"?
                                        <span className={this.getRenderStyle(history.profit) }>{ parseFloat(history.profit).toFixed(2) }%</span>
                                        :
                                        "—"  
                                      }
                                    </p>
                                    <p>
                                      持有&nbsp;{
                                        parseFloat(history.positiondays)>0?
                                        `${history.positiondays}`
                                        :
                                        `--`
                                      }&nbsp;天
                                    </p>
                                </Col>
                                <Col xs={2}>
                                    <p className="text-danger product-data-single product-data-like" onClick={ this.handleHistoryLike.bind(this, history)}>
                                        <i className="iconfont icon-praise"></i>&nbsp;
                                          {
                                            parseInt(history.praisenum||"0")>=0?
                                            `${history.praisenum}`
                                            :
                                            `0`
                                          }
                                    </p>
                                </Col>
                              </Row>
                          );
                      })
                      :
                      <div className="text-center">
                          暂无操作历史
                      </div>
                    }
                  </Panel>

                  <div className="devider">
                  </div>

                  <div className="padding text-center">
                    {
                      user.isauth === "1"?
                      <Link to={`/ProductDetail`}  query={{id:product.gsid}}>
                        <Button bsStyle="primary" block>
                            查看更多详情
                        </Button>
                      </Link>
                      :
                      <div>
                        <small className="text-muted">绑定证券账户，查看更多详情 &nbsp;</small>
                        <Link to={`/Bind`}>
                          <Button bsStyle="primary" className="btn-spread" bsSize="sm">
                            绑定
                          </Button>
                        </Link>
                      </div>
                    }
                  </div>
              </div>
            </Collapse>
          </Panel>
      );
  }
}

export default ProductItem;